<template>
  <div class="partner-manage-page">
    <el-card class="search-card">
      <el-row :gutter="20" class="search-row">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="아이디/이름/초대코드 검색"
            clearable
            @keyup.enter="loadPartners"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchStatus" placeholder="상태 선택" clearable>
            <el-option label="전체" value="" />
            <el-option label="활성" value="ACTIVE" />
            <el-option label="비활성" value="INACTIVE" />
            <el-option label="정지" value="SUSPENDED" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadPartners">
            <el-icon><Search /></el-icon> 검색
          </el-button>
          <el-button @click="resetSearch">초기화</el-button>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon> 파트너 추가
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="partners"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="아이디" width="150" />
        <el-table-column prop="name" label="이름" width="120" />
        <el-table-column prop="partnerCode" label="초대 코드" width="150">
          <template #default="{ row }">
            <el-tag type="success">{{ row.partnerCode }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="추천 링크" width="280">
          <template #default="{ row }">
            <div class="referral-link-container">
              <el-input
                :value="getReferralLink(row.partnerCode)"
                readonly
                size="small"
                class="referral-link-input"
              />
              <el-button
                size="small"
                type="primary"
                @click="copyReferralLink(row.partnerCode)"
                :icon="CopyDocument"
              >
                복사
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="회원 수" width="100" align="center" />
        <el-table-column prop="status" label="상태" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="생성일" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="작업" fixed="right" width="280">
          <template #default="{ row }">
            <el-button size="small" @click="showUsers(row)">회원 보기</el-button>
            <el-button size="small" type="primary" @click="showEditDialog(row)">편집</el-button>
            <el-dropdown @command="handleCommand($event, row)">
              <el-button size="small">
                더보기 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="status">상태 변경</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>삭제</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadPartners"
        @current-change="loadPartners"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '파트너 편집' : '파트너 추가'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="아이디" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="로그인 아이디"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="이름" prop="name">
          <el-input v-model="formData.name" placeholder="파트너 이름" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="비밀번호" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="비밀번호 (6자 이상)"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="isEdit" label="새 비밀번호" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="변경하지 않으려면 비워두세요"
            show-password
          />
        </el-form-item>
        <el-form-item label="초대 코드" prop="partnerCode">
          <el-input
            v-model="formData.partnerCode"
            placeholder="비워두면 자동 생성됩니다"
          >
            <template #append>
              <el-button @click="generateCode">자동 생성</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">취소</el-button>
        <el-button type="primary" @click="submitForm">확인</el-button>
      </template>
    </el-dialog>

    <!-- 会员列表对话框 -->
    <el-dialog v-model="usersDialogVisible" title="파트너 회원 목록" width="800px">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <span>파트너 회원 목록</span>
          <el-button type="primary" size="small" @click="showAddUserDialog">
            <el-icon><Plus /></el-icon> 회원 추가
          </el-button>
        </div>
      </template>
      <el-table :data="partnerUsers" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="idNumber" label="주민등록번호" width="150" />
        <el-table-column prop="name" label="이름" width="120" />
        <el-table-column prop="status" label="상태" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="가입일" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="addUserDialogVisible"
      title="회원 추가"
      width="700px"
      append-to-body
    >
      <el-row :gutter="10" style="margin-bottom: 15px">
        <el-col :span="18">
          <el-input
            v-model="availableSearchKeyword"
            placeholder="이름/주민등록번호/휴대폰 번호 검색"
            clearable
            @keyup.enter="loadAvailableUsers"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadAvailableUsers">검색</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="availableUsers"
        @selection-change="handleSelectionChange"
        stripe
        max-height="400"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="이름" width="100" />
        <el-table-column prop="idNumber" label="주민등록번호" width="150" />
        <el-table-column prop="mobileNumber" label="휴대폰" width="130" />
        <el-table-column prop="status" label="상태" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="availablePagination.page"
        v-model:page-size="availablePagination.limit"
        :total="availablePagination.total"
        layout="total, prev, pager, next"
        style="margin-top: 15px; justify-content: flex-end"
        @current-change="loadAvailableUsers"
      />

      <template #footer>
        <el-button @click="addUserDialogVisible = false">취소</el-button>
        <el-button
          type="primary"
          :disabled="selectedUserIds.length === 0"
          @click="submitAddUsers"
        >
          확인 ({{ selectedUserIds.length }}명 추가)
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus, ArrowDown, CopyDocument } from '@element-plus/icons-vue'
import request from '@/utils/request'

type PartnerStatus = 'ACTIVE' | 'INACTIVE' | 'SUSPENDED'
type DropdownCommand = 'status' | 'delete'

interface Partner {
  id: number
  username: string
  name: string
  role: string
  status: PartnerStatus
  isPartner: boolean
  partnerCode: string
  userCount: number
  createdAt: string
  updatedAt: string
}

interface PartnerUser {
  id: number
  idNumber: string
  name: string
  status: PartnerStatus
  createdAt: string
}

interface AvailableUser {
  id: number
  name: string
  idNumber: string
  mobileNumber: string
  status: PartnerStatus
}

interface PaginationMeta {
  total: number
}

interface PartnerListResponse {
  partners: Partner[]
  pagination: PaginationMeta
}

interface PartnerUsersResponse {
  users: PartnerUser[]
}

interface AvailableUsersResponse {
  users: AvailableUser[]
  pagination: PaginationMeta
}

const loading = ref(false)
const partners = ref<Partner[]>([])
const searchKeyword = ref('')
const searchStatus = ref('')

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive({
  id: 0,
  username: '',
  name: '',
  password: '',
  partnerCode: ''
})

const formRules: FormRules = {
  username: [{ required: true, message: '아이디를 입력해 주세요', trigger: 'blur' }],
  name: [{ required: true, message: '이름을 입력해 주세요', trigger: 'blur' }],
  password: [
    {
      validator: (rule, value, callback) => {
        if (!isEdit.value && !value) {
          callback(new Error('비밀번호를 입력해 주세요'))
        } else if (value && value.length < 6) {
          callback(new Error('비밀번호는 최소 6자 이상이어야 합니다'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const usersDialogVisible = ref(false)
const partnerUsers = ref<PartnerUser[]>([])
const currentPartnerId = ref(0)

// 添加用户相关
const addUserDialogVisible = ref(false)
const availableUsers = ref<AvailableUser[]>([])
const selectedUserIds = ref<number[]>([])
const availableSearchKeyword = ref('')
const availablePagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 加载合作伙伴列表
const loadPartners = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }
    if (searchKeyword.value) params.keyword = searchKeyword.value
    if (searchStatus.value) params.status = searchStatus.value

    const response = await request.get<PartnerListResponse>('/api/admin/partners', { params })
    partners.value = response.data.partners
    pagination.total = response.data.pagination.total
  } catch (error: any) {
    ElMessage.error(error.message || '파트너 목록 로딩 실패')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  searchStatus.value = ''
  pagination.page = 1
  loadPartners()
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  formData.id = 0
  formData.username = ''
  formData.name = ''
  formData.password = ''
  formData.partnerCode = ''
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: Partner) => {
  isEdit.value = true
  formData.id = row.id
  formData.username = row.username
  formData.name = row.name
  formData.password = ''
  formData.partnerCode = row.partnerCode
  dialogVisible.value = true
}

// 生成随机邀请码
const generateCode = () => {
  formData.partnerCode = Math.random().toString(36).substring(2, 10).toUpperCase()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (isEdit.value) {
        const data: any = { name: formData.name }
        if (formData.password) data.password = formData.password
        if (formData.partnerCode) data.partnerCode = formData.partnerCode

        await request.put(`/api/admin/partners/${formData.id}`, data)
        ElMessage.success('파트너 정보가 성공적으로 업데이트되었습니다')
      } else {
        await request.post('/api/admin/partners', {
          username: formData.username,
          name: formData.name,
          password: formData.password,
          partnerCode: formData.partnerCode || undefined
        })
        ElMessage.success('파트너가 성공적으로 추가되었습니다')
      }
      dialogVisible.value = false
      loadPartners()
    } catch (error: any) {
      ElMessage.error(error.message || '작업 실패')
    }
  })
}

// 查看合作伙伴的会员
const showUsers = async (row: Partner) => {
  currentPartnerId.value = row.id
  try {
    const response = await request.get<PartnerUsersResponse>(`/api/admin/partners/${row.id}/users`)
    partnerUsers.value = response.data.users
    usersDialogVisible.value = true
  } catch (error: any) {
    ElMessage.error(error.message || '회원 목록 로딩 실패')
  }
}

// 处理命令
const handleCommand = async (command: DropdownCommand, row: Partner) => {
  if (command === 'status') {
    changeStatus(row)
  } else if (command === 'delete') {
    deletePartner(row)
  }
}

// 更改状态
const changeStatus = async (row: Partner) => {
  try {
    const { value } = await ElMessageBox.prompt(
      '상태 값을 입력하세요 (ACTIVE / INACTIVE / SUSPENDED)',
      '상태 변경',
      {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
        inputValue: row.status,
        inputPattern: /^(ACTIVE|INACTIVE|SUSPENDED)$/i,
        inputErrorMessage: 'ACTIVE, INACTIVE, SUSPENDED 중 하나를 입력해 주세요.'
      }
    )

    const normalizedStatus = value.toUpperCase() as PartnerStatus
    await request.post(`/api/admin/partners/${row.id}/status`, { status: normalizedStatus })
    ElMessage.success('상태가 성공적으로 변경되었습니다')
    loadPartners()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '상태 변경 실패')
    }
  }
}

// 删除合作伙伴
const deletePartner = async (row: Partner) => {
  try {
    await ElMessageBox.confirm(
      `정말로 파트너 "${row.name}"을(를) 삭제하시겠습니까?`,
      '파트너 삭제',
      {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
        type: 'warning'
      }
    )

    await request.delete(`/api/admin/partners/${row.id}`)
    ElMessage.success('파트너가 성공적으로 삭제되었습니다')
    loadPartners()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '파트너 삭제 실패')
    }
  }
}

const STATUS_TAG_TYPE: Record<PartnerStatus, 'success' | 'info' | 'danger'> = {
  ACTIVE: 'success',
  INACTIVE: 'info',
  SUSPENDED: 'danger'
}

const STATUS_TEXT: Record<PartnerStatus, string> = {
  ACTIVE: '활성',
  INACTIVE: '비활성',
  SUSPENDED: '정지'
}

const getStatusType = (status: PartnerStatus) => {
  return STATUS_TAG_TYPE[status] ?? 'info'
}

const getStatusText = (status: PartnerStatus) => {
  return STATUS_TEXT[status] ?? status
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString('ko-KR')
}

// 生成推广链接
const getReferralLink = (partnerCode: string) => {
  return `https://my-nearwallet.com/register?entryCode=${partnerCode}`
}

// 复制推广链接到剪贴板
const copyReferralLink = async (partnerCode: string) => {
  const link = getReferralLink(partnerCode)
  try {
    await navigator.clipboard.writeText(link)
    ElMessage.success('추천 링크가 클립보드에 복사되었습니다')
  } catch (error) {
    // 降级方案：使用传统方法复制
    const textArea = document.createElement('textarea')
    textArea.value = link
    textArea.style.position = 'fixed'
    textArea.style.left = '-999999px'
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('추천 링크가 클립보드에 복사되었습니다')
    } catch (err) {
      ElMessage.error('복사에 실패했습니다. 수동으로 복사해 주세요.')
    }
    document.body.removeChild(textArea)
  }
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  availableSearchKeyword.value = ''
  availablePagination.page = 1
  selectedUserIds.value = []
  addUserDialogVisible.value = true
  loadAvailableUsers()
}

// 加载可添加的用户列表
const loadAvailableUsers = async () => {
  try {
    const params: Record<string, string | number> = {
      page: availablePagination.page,
      limit: availablePagination.limit
    }
    if (availableSearchKeyword.value) {
      params.search = availableSearchKeyword.value
    }

    const response = await request.get<AvailableUsersResponse>('/api/admin/partners/available-users', { params })
    availableUsers.value = response.data.users
    availablePagination.total = response.data.pagination.total
  } catch (error: any) {
    ElMessage.error(error.message || '사용 가능한 회원 목록 로딩 실패')
  }
}

// 处理用户选择
const handleSelectionChange = (selection: AvailableUser[]) => {
  selectedUserIds.value = selection.map((user) => user.id)
}

// 提交添加用户
const submitAddUsers = async () => {
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning('추가할 회원을 선택해 주세요.')
    return
  }

  try {
    await request.post(`/api/admin/partners/${currentPartnerId.value}/users`, {
      userIds: selectedUserIds.value
    })
    ElMessage.success(`${selectedUserIds.value.length}명의 회원이 성공적으로 추가되었습니다.`)
    addUserDialogVisible.value = false
    // 刷新合作伙伴用户列表
    showUsers({ id: currentPartnerId.value } as Partner)
  } catch (error: any) {
    ElMessage.error(error.message || '회원 추가 실패')
  }
}

onMounted(() => {
  loadPartners()
})
</script>

<style scoped lang="scss">
.partner-manage-page {
  .search-card {
    margin-bottom: 20px;

    .search-row {
      align-items: center;
    }
  }

  .table-card {
    .el-pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }

  .text-right {
    text-align: right;
  }

  .referral-link-container {
    display: flex;
    gap: 8px;
    align-items: center;

    .referral-link-input {
      flex: 1;

      :deep(.el-input__wrapper) {
        font-size: 12px;
      }
    }
  }
}
</style>
